package com.topvision.camerasdk.album;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.topvision.camerasdk.R;
import com.topvision.camerasdk.album.adapter.PhotoGridAdapter;
import com.topvision.camerasdk.album.adapter.ShowPicAdapter;
import com.topvision.camerasdk.album.entity.MessageEvent;
import com.topvision.camerasdk.album.sensor.ParallelViewHelper;
import com.topvision.camerasdk.album.utils.MotionEventUtil;
import com.topvision.camerasdk.album.view.PhotoView;
import com.topvision.camerasdk.album.view.ThumbnailView;
import com.topvision.camerasdk.camera.BitmapWorkerTask;
import com.topvision.camerasdk.camera.CameraConstants;
import com.topvision.camerasdk.video.util.VideoConstant;
import com.topvision.commomsdk.TouchInterface;
import com.topvision.commomsdk.commom.Album;
import com.topvision.commomsdk.uitl.AndroidUtils;
import com.topvision.commomsdk.uitl.FileUtil;
import com.topvision.commomsdk.view.TvViewPager;
import com.topvision.voicesdk.BaseVoiceActivity;
import com.topvision.voicesdk.CommonVoice;
import com.topvision.voicesdk.VoiceInterface;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;


public class ShowPicActivity extends BaseVoiceActivity implements VoiceInterface, ViewPager.OnPageChangeListener, ThumbnailView.ThumbnailListener, ParallelViewHelper.PhotoViewScaleListener, TouchInterface {
    public static final String ALBUM_KEY = "album_key";
    public static final String SHOW_MENU_TIME = "show_menu_time";
    //图片对象改变
    public static final String PHOTO_VIEW_DATA_CHANGE = "photo_view_change";
    //所有图片对象
    ArrayList<Album> list;
    //当前选中图片位置
    int currentPosition = 0;
    private TvViewPager viewPager;
    //存放视频控件
    private ArrayList<View> pagerView;
    //当前照片对象内容
    private Album album;
    public Context context;
    public static ShowPicActivity showPicActivity = null;
    ArrayList<PhotoView> imageViews;
    ArrayList<ThumbnailView> thumbnailViews;
    TextView textPager;
    TextView voiceTips;
    MyReceiver myReceiver;


    //放大缩小图片用到的参数
    int screenHeight;
    int screenWidth;
    //当前放大缩小移动位置x轴的点坐标
    //当前放大缩小移动位置y轴的点坐标
    int x = 0;
    int y = 0;
    public static ParallelViewHelper parallelViewHelper;
    public static boolean sensorFlag = true;
    ImageView currentPhotoView = null;
    private PagerAdapter mPagerAdapter;
    //放大指示器
    private LinearLayout picSelector_ll;
    private TextView picSelector_1;
    private TextView picSelector_2;
    private TextView picSelector_3;
    private TextView picSelector_4;
    private int zoomInCount;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_show_pic);
        //hiddenNavigator();
        showPicActivity = this;
        context = this;
        sensorFlag = true;
        initUi();
        initData();
//        TvSdk.startHeadTrack(context);
        EventBus.getDefault().register(this);
    }

    /**
     * 初始化UI
     *
     * @author jack
     * create at 2016/11/22 16:46
     */
    private void initUi() {
        viewPager = (TvViewPager) findViewById(R.id.viewPager);
        viewPager.setOnPageChangeListener(this);
        voiceTips = (TextView) findViewById(R.id.shop_pic_voice_tips);
        textPager = (TextView) findViewById(R.id.tv_page);

        //图片放大指示器
        picSelector_ll = (LinearLayout) findViewById(R.id.pic_selector_ll);
        picSelector_1 = (TextView) findViewById(R.id.pic_selector_1);
        picSelector_2 = (TextView) findViewById(R.id.pic_selector_2);
        picSelector_3 = (TextView) findViewById(R.id.pic_selector_3);
        picSelector_4 = (TextView) findViewById(R.id.pic_selector_4);

        if (!getIntent().getBooleanExtra(CameraConstants.VOICE_TIPS_FLAG, false)) {
            voiceTips.setVisibility(View.GONE);
        }
    }

    private void initData() {
        screenWidth = AndroidUtils.getScreenWidth(context, getWindowManager());
        screenHeight = AndroidUtils.getScreenHeight(context, getWindowManager());
        list = getIntent().getParcelableArrayListExtra(VideoConstant.ALBUM_KEY);
        currentPosition = getIntent().getIntExtra(
                PhotoGridAdapter.CURRENT_POSITON, 0);
        pagerView = new ArrayList<>();
        imageViews = new ArrayList<>();
        thumbnailViews = new ArrayList<>();
        //循环遍历封裝View
        LayoutInflater inflater = getLayoutInflater();
        for (int i = 0; i < list.size(); i++) {
            View convertView = inflater.inflate(R.layout.activity_camera_show_pic_item, null);
            PhotoView im_ico = (PhotoView) convertView
                    .findViewById(R.id.im_ico);
            ThumbnailView thumbnailView = (ThumbnailView) convertView.findViewById(R.id.thumbnail);
            //注册回调方法
            thumbnailView.setOnThumbnailListener(ShowPicActivity.this);
            //允许放大缩小
            im_ico.enable();
            album = list.get(i);
            if (currentPosition == i) {
                //异步加载图片
                new BitmapWorkerTask(context, im_ico).execute(album.getPath());
                new BitmapWorkerTask(context, thumbnailView).execute(album.getPath());
            }
            imageViews.add(im_ico);
            thumbnailViews.add(thumbnailView);
            pagerView.add(convertView);
        }
        mPagerAdapter = new ShowPicAdapter(pagerView);
        viewPager.setAdapter(mPagerAdapter);
        //设置ViewPager当前页数
        viewPager.setCurrentItem(currentPosition);
        currentPhotoView = imageViews.get(currentPosition);
        //设置页码
        textPager.setText((viewPager.getCurrentItem() + 1) + "/" + pagerView.size());
        //初始化parallelViewHelper
        parallelViewHelper = new ParallelViewHelper(context);
        //注册回调方法
        parallelViewHelper.setOnBigPicMoveListener(this);
        //初始化画笔工具
        initPaint();
    }

    private Paint mPaint;
    private Rect mRect;
    private void initPaint() {
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(3);
        mPaint.setColor(Color.RED);
        mRect = new Rect();
    }
    /**
     * 原图移动回调
     * @param viewWidth
     * @param viewHeight
     * @param currentShiftX
     * @param currentShiftY
     */
    int mCurrentShiftX;
    int mCurrentShiftY;
    boolean isMove;
    @Override
    public void onPhotoViewScale(float currentShiftX, float currentShiftY) {
        isMove = true;
        mCurrentShiftX = (int) (currentShiftX * currentThumbnailView.realWidth / mViewWidth / 2);
        if (isTwo) {
            mCurrentShiftY = (int) ((3.0f / 4) * currentShiftY * currentThumbnailView.realHeight / mViewHeight / 2);
        } else {
            mCurrentShiftY = (int) (currentShiftY * currentThumbnailView.realHeight / mViewHeight / 2);
        }
        currentThumbnailView.invalidate();
    }

    /**
     * 原图放大回调，最先执行
     *
     * @param tempRadio
     */
    private int mDistancePX;
    private int mViewWidth;
    private int mViewHeight;
    ThumbnailView currentThumbnailView;
    private boolean isTwo;
    @Override
    public void onPhotoViewZoomUp(int distancePX, int viewWidth, int viewHeight) {
        mDistancePX = distancePX / 2;
        if (mDistancePX == 160) {
            isTwo = true;
        } else {
            isTwo = false;
        }
        mViewWidth = viewWidth;
        mViewHeight = viewHeight;
        System.out.println("radio===>"+mDistancePX);
        currentThumbnailView = thumbnailViews.get(viewPager.getCurrentItem());
        currentThumbnailView.invalidate();
    }

    private int leftTopX;
    private int leftTopY;
    private int rightBottomX;
    private int rightBottomY;
    private boolean isShow;
    /**
     * 缩略图回调
     * @param canvas
     */
    @Override
    public void onThumbnail(Canvas canvas) {
        if (imageViews.get(viewPager.getCurrentItem()).isEnoughSmall || isNextOrPre) {
            isNextOrPre = false;
            mRect.set(0,0,0,0);
            canvas.drawRect(mRect,mPaint);
            return;
        }
        //放大缩小图片的回调(显示已经没有问题)
        if (mDistancePX != 0) {
            if (mViewWidth != 0 && mViewHeight != 0 && mPaint != null) {
                //计算矩形的坐标值
                leftTopX = ((mDistancePX == 120 ? 140 : mDistancePX) * currentThumbnailView.realWidth / mViewWidth);
                leftTopY = ((mDistancePX == 160 ? 120 : mDistancePX) * currentThumbnailView.realHeight / mViewHeight);
                rightBottomX = currentThumbnailView.realWidth - (mDistancePX * currentThumbnailView.realWidth / mViewWidth);
                rightBottomY = currentThumbnailView.realHeight - ((mDistancePX == 160 ? 120 : mDistancePX) * currentThumbnailView.realHeight / mViewHeight);
                //画矩形
                mRect.set(leftTopX,leftTopY,rightBottomX,rightBottomY);
                canvas.drawRect(mRect, mPaint);
            }
            //再将放大缩小事件和值至为零
            mDistancePX = 0;
            mDistancePX = 0;
            //TODO 是头部移动的回调（计算上存在问题，继续研究）(完成)
        } else if ((isMove && mViewWidth != 0 && mViewHeight != 0 && mPaint != null) || isShow){
            isShow = false;
            isMove = false;
            //画矩形
            mRect.set(leftTopX-mCurrentShiftX,leftTopY-mCurrentShiftY,rightBottomX-mCurrentShiftX,rightBottomY-mCurrentShiftY);
            canvas.drawRect(mRect,mPaint);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        TvSdk.stopHeadTrack(context);
        //停止头部控制
        parallelViewHelper.stop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setTouchInterfaceListener(this);
        setVoiceInterfaceListener(this);
        registerMyReceiver();
    }


    @Override
    protected void onPause() {
        super.onPause();
        setTouchInterfaceListener(null);
        setVoiceInterfaceListener(null);
        unregisterMyReceiver();

    }


    /**
     * 对一些图片的特殊功能,如蓝牙分享、删除
     *
     * @author jack
     * create at 2016/11/22 16:51
     */
    private void choose() {
        showPhotoMenu(System.currentTimeMillis());
    }

    /**
     * 显示相册菜单列表
     *
     * @param showMenuTime 显示菜单当时的时间戳
     *                     create at 2016/11/23 16:13
     * @author jack
     */
    //是否正在加载图片
    public static boolean isloading = true;
    private void showPhotoMenu(long showMenuTime) {
        if (!isloading) {
            Intent photoMenu = new Intent(context, PhotoMenuActivity.class);
            //获取当前图片信息
            album = list.get(viewPager.getCurrentItem());
            photoMenu.putExtra(ALBUM_KEY, album);
            photoMenu.putExtra(SHOW_MENU_TIME, showMenuTime);
            startActivity(photoMenu);
        }
    }

    /**
     * 下张图片
     *
     * @author jack
     * create at 2016/12/9 14:27
     */
    private void nextPhoto() {
        if (currentPosition + 1 < list.size()) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
        } else {
            AndroidUtils.showTips(this, getResources().getString(R.string.last_one_pic));
        }
    }


    /**
     * 上张图片
     *
     * @author jack
     * create at 2016/12/9 14:27
     */
    private void previousPhoto() {
        if (currentPosition > 0) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
        } else {
            AndroidUtils.showTips(this, getResources().getString(R.string.first_one_pic));
        }
    }

    private void switchZoomCount(int zoomInCount) {
        switch (zoomInCount) {
            case 0:
                picSelector_1.setSelected(false);
                picSelector_2.setSelected(false);
                picSelector_3.setSelected(false);
                picSelector_4.setSelected(false);
                picSelector_ll.setVisibility(View.GONE);
                break;
            case 1:
                picSelector_1.setSelected(true);
                picSelector_2.setSelected(false);
                picSelector_3.setSelected(false);
                picSelector_4.setSelected(false);
                picSelector_ll.setVisibility(View.VISIBLE);
                break;
            case 2:
                picSelector_1.setSelected(false);
                picSelector_2.setSelected(true);
                picSelector_3.setSelected(false);
                picSelector_4.setSelected(false);
                picSelector_ll.setVisibility(View.VISIBLE);
                break;
            case 3:
                picSelector_1.setSelected(false);
                picSelector_2.setSelected(false);
                picSelector_3.setSelected(true);
                picSelector_4.setSelected(false);
                picSelector_ll.setVisibility(View.VISIBLE);
                break;
            case 4:
                picSelector_1.setSelected(false);
                picSelector_2.setSelected(false);
                picSelector_3.setSelected(false);
                picSelector_4.setSelected(true);
                picSelector_ll.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 放大缩小图片
     * @param photoView
     * @param data 语音结果
     * @param up 放大or缩小
     */
    private void zoomUpPic(PhotoView photoView, String data,boolean up) {
        if (up) {//如果是放大
            if (data.contains("一倍") || data.contains("两倍") || data.contains("三倍") || data.contains("四倍")) {
                if (data.contains("一倍")) {
                    zoomInCount = 1;
                } else if (data.contains("两倍")) {
                    zoomInCount = 2;
                } else if (data.contains("三倍")) {
                    zoomInCount = 3;
                } else if (data.contains("四倍")) {
                    zoomInCount = 4;
                }
            }
        } else {//如果是缩小
//            x = screenWidth / 2;
//            y = screenHeight / 2;
            zoomInCount = 0;
        }
        photoView.voiceZoom(up,zoomInCount);
        switchZoomCount(zoomInCount);
    }

    @Override
    public void dealWithVoice(String data) {
        data = data.toLowerCase();
        //获取当前图片控件
        PhotoView photoView = imageViews.get(currentPosition);
        if (data.contains(CommonVoice.VOICE_ZH_ZOOM_IN) || data.equalsIgnoreCase(CommonVoice.VOICE_US_ZOOM_IN)) {
            //倍率指示器显示（放大）
            if (zoomInCount < 4) {
                zoomInCount++;
            }
            //顺序要在后面
            zoomUpPic(photoView, data, true);
        } else if (data.equals(CommonVoice.VOICE_ZH_ZOOM_OUT) || data.equalsIgnoreCase(CommonVoice.VOICE_US_ZOOM_OUT)) {
            //直接缩小至原图
            zoomUpPic(photoView, data, false);
        } else if (data.equals(CommonVoice.VOICE_ZH_LIFT) || data.equalsIgnoreCase(CommonVoice.VOICE_US_LIFT)) {
            //处于放大的情况下能执行左移动和右移动
            if (photoView.isZoonUp()) {
                if (x == 0 && y == 0) {
                    x = screenWidth / 2;
                    y = screenHeight / 2;
                } else {
                    x = x + 60;
                }
                //反方向
                MotionEventUtil.simulateMoveRight(photoView, x, y);
            } else {
                previousPhoto();
            }
        } else if (data.equals(CommonVoice.VOICE_ZH_RIGHT) || data.equalsIgnoreCase(CommonVoice.VOICE_US_RIGHT)){
            if (photoView.isZoonUp()) {
                if (x == 0 && y == 0) {
                    x = screenWidth / 2;
                    y = screenHeight / 2;
                } else {
                    x = x - 60;
                }
                //反方向
                MotionEventUtil.simulateMoveLeft(photoView, x, y);
            } else {
                nextPhoto();
            }
        } else if (data.equals(CommonVoice.VOICE_ZH_DOWN) || data.equalsIgnoreCase(CommonVoice.VOICE_US_DOWN)) {
            if (photoView.isZoonUp()) {
                if (x == 0 && y == 0) {
                    x = screenWidth / 2;
                    y = screenHeight / 2;
                } else {
                    //因为是横屏，所以y轴变化比x轴小
                    y = y - 30;
                }
                //反方向
                MotionEventUtil.simulateMoveUp(photoView, x, y);
            } else {
                nextPhoto();
            }
        } else if (data.equals(CommonVoice.VOICE_ZH_UP) || data.equalsIgnoreCase(CommonVoice.VOICE_US_UP)) {
            if (photoView.isZoonUp()) {
                if (x == 0 && y == 0) {
                    x = screenWidth / 2;
                    y = screenHeight / 2;
                } else {
                    //因为是横屏，所以y轴变化比x轴小
                    y = y + 30;
                }
                //反方向
                MotionEventUtil.simulateMoveDown(photoView, x, y);
            } else {
                previousPhoto();
            }
        } else if (data.equals(CommonVoice.VOICE_ZH_DELETE) || data.equalsIgnoreCase(CommonVoice.VOICE_US_DELETE)) {
            deletePhoto();
        } else if (data.equals(CommonVoice.VOICE_ZH_MENU) || data.equalsIgnoreCase(CommonVoice.VOICE_US_MENU)) {
            showPhotoMenu(System.currentTimeMillis());
        } else if (data.equals(CommonVoice.VOICE_ZH_BACK) || data.equalsIgnoreCase(CommonVoice.VOICE_US_BACK)) {
            finish();
        } else if (data.equals(CommonVoice.VOICE_ZH_FREEZE) || data.equalsIgnoreCase(CommonVoice.VOICE_US_FREEZE)) {
            photoView.stopHeadTrack();
        } else if (data.equals(CommonVoice.VOICE_ZH_RESUME) || data.equalsIgnoreCase(CommonVoice.VOICE_US_RESUME)) {
            photoView.startHeadTrack();
        } else if (data.equals(CommonVoice.VOICE_ZH_HIDE) || data.equalsIgnoreCase(CommonVoice.VOICE_US_HIDE)) {
            if (currentThumbnailView != null) {
                currentThumbnailView.setVisibility(View.GONE);
            }
        } else if (data.equals(CommonVoice.VOICE_ZH_SHOW) || data.equalsIgnoreCase(CommonVoice.VOICE_US_SHOW)) {
            if (currentThumbnailView != null) {
                isShow = true;
                currentThumbnailView.invalidate();
                currentThumbnailView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 刪除照片
     *
     * @author jack
     * create at 2016/11/23 11:41
     */
    private void deletePhoto() {
        album = list.get(viewPager.getCurrentItem());
        //原始图片路径
        String albumPath = album.getPath();
        //缩略图路径
        String thumbnailPath = album.getThumbnailPath();
        boolean albumFlag = FileUtil.removeFile(context, albumPath);
        boolean thumbnailFlag = FileUtil.removeFile(context, thumbnailPath);
        boolean isSuccess = false;
        if (!albumFlag && !thumbnailFlag) {
//            AndroidUtils.showTips(context,getString(R.string.delete_failed));

        } else {
            isSuccess = true;
        }
        sendUpdatePhotoBroadcast(isSuccess);
        finish();
    }

    /**
     * 发送更新相册广播
     *
     * @author jack
     * create at 2016/11/23 17:41
     */
    private void sendUpdatePhotoBroadcast(boolean isSuccess) {
        Intent intent = new Intent(MyAblumActivity.ACTION_UPDATE_ALBUM);
        sendBroadcast(intent);
    }


    //以上是监听viewpager翻頁滑动事件
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }
    boolean isNextOrPre;
    @Override
    public void onPageSelected(int position) {
        currentPosition = position;
        currentPhotoView = imageViews.get(currentPosition);
        album = list.get(currentPosition);
        //发送广播告诉头部控制操作对象改变
        Intent photoViewIntent = new Intent(PHOTO_VIEW_DATA_CHANGE);
        sendBroadcast(photoViewIntent);
        new BitmapWorkerTask(context, imageViews.get(currentPosition)).execute(list.get(currentPosition).getPath());
        new BitmapWorkerTask(context, thumbnailViews.get(currentPosition)).execute(list.get(currentPosition).getPath());
        //设置页码
        textPager.setText((position+1)+"/"+pagerView.size());
        isNextOrPre = true;
    }


    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void doForwardTouch() {

    }

    @Override
    public void doBackwardTouch() {

    }

    @Override
    public void doClickTouch() {
        showPhotoMenu(System.currentTimeMillis());
    }

    @Override
    public void doDoubleTouch() {

    }

    public class MyReceiver extends BroadcastReceiver {
        //关闭当前视图
        public static final String ACTION_FINISH_ACTIVITY = "ACTION_FINISH_ACTIVITY";
        //显示菜单
        public static final String ACTION_SHOW_MENU = "ACTION_SHOW_MENU";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_FINISH_ACTIVITY.equals(action)) {
                finish();
            } else if (ACTION_SHOW_MENU.equals(action)) {
                showPhotoMenu(System.currentTimeMillis());
            }

        }
    }

    private void registerMyReceiver() {
        if (myReceiver == null) {
            myReceiver = new MyReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MyReceiver.ACTION_FINISH_ACTIVITY);
        intentFilter.addAction(MyReceiver.ACTION_SHOW_MENU);
        registerReceiver(myReceiver, intentFilter);
    }

    private void unregisterMyReceiver() {
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
    }


    /**
     * 该方法主要使用用来图片放大后的移动操作
     * create at 2016/12/21 13:29
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void picEventMessage(MessageEvent message) {
//        int x = message.getX();
//        int y = message.getY();
//        if (!currentPhotoView.isZoonUp()) {
//            return;
//        }
//        switch (message.getMsgType()) {
//            case HeadTrackService.PIC_MOVE_LEFT:
//                MotionEventUtil.simulateMoveLeft(currentPhotoView, x, y);
//                break;
//            case HeadTrackService.PIC_MOVE_RIGHT:
//                MotionEventUtil.simulateMoveRight(currentPhotoView, x, y);
//                break;
//            case HeadTrackService.PIC_MOVE_UP:
//                MotionEventUtil.simulateMoveUp(currentPhotoView, x, y);
//                break;
//            case HeadTrackService.PIC_MOVE_DOWN:
//                MotionEventUtil.simulateMoveDown(currentPhotoView, x, y);
//                break;
//        }

    }

    public ImageView getCurrentPhotoView() {
        return currentPhotoView;
    }
}


